package com.qc31.monitorlib.ui.video

import android.app.Activity
import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.view.Window
import com.qc31.monitorlib.R
import com.shuyu.gsyvideoplayer.GSYVideoBaseManager
import com.shuyu.gsyvideoplayer.model.VideoOptionModel
import com.shuyu.gsyvideoplayer.player.IPlayerManager
import com.shuyu.gsyvideoplayer.player.IjkPlayerManager
import com.shuyu.gsyvideoplayer.utils.CommonUtil
import com.shuyu.gsyvideoplayer.video.base.GSYVideoPlayer
import tv.danmaku.ijk.media.player.IjkMediaPlayer

/**
 *@Author Jasper
 *@Time   2020/9/11
 *@Desc   多视频播放视频管理器
 */
class RealVideoManager : GSYVideoBaseManager() {

    init {
        init()
        initVideoOption()
        isNeedMute = true
    }

    override fun getPlayManager(): IPlayerManager {
        return IjkPlayerManager()
    }

    companion object {
        val SMALL_ID: Int = R.id.custom_small_id
        val FULLSCREEN_ID: Int = R.id.custom_full_id
        private val S_MAP: HashMap<String, RealVideoManager> = HashMap()

        /**
         * 单例管理器
         */
        @Synchronized
        fun instance(): Map<String, RealVideoManager> {
            return S_MAP
        }

        /**
         * 退出全屏，主要用于返回键
         *
         * @return 返回是否全屏
         */
        fun backFromWindowFull(context: Context, key: String): Boolean {
            var backFrom = false
            val vp =
                CommonUtil.scanForActivity(context)
                    .findViewById<View>(Window.ID_ANDROID_CONTENT) as ViewGroup
            val oldF = vp.findViewById<View>(FULLSCREEN_ID)
            if (oldF != null) {
                backFrom = true
                CommonUtil.hideNavKey(context)
                if (getCustomManager(key).lastListener() != null) {
                    getCustomManager(key).lastListener().onBackFullscreen()
                }
            }
            return backFrom
        }


        /**
         * 页面销毁了记得调用是否所有的video
         */
        fun releaseAllVideos(key: String) {
            if (getCustomManager(key).listener() != null) {
                getCustomManager(key).listener().onCompletion()
            }
            getCustomManager(key).releaseMediaPlayer()
        }

        /**
         * 单例管理器
         */
        @Synchronized
        fun getCustomManager(key: String): RealVideoManager {
            var realVideoManager: RealVideoManager? = S_MAP[key]
            if (realVideoManager == null) {
                realVideoManager = RealVideoManager()
                S_MAP[key] = realVideoManager
            }
            return realVideoManager
        }

        fun onPauseAll() {
            if (S_MAP.isNotEmpty()) {
                for ((key, value) in S_MAP.entries) {
                    value.onPause(key)
                }
            }
        }

        fun onResumeAll() {
            if (S_MAP.isNotEmpty()) {
                for ((key, value) in S_MAP.entries) {
                    value.onResume(key)
                }
            }
        }

        /**
         * 恢复暂停状态
         *
         * @param seek 是否产生seek动作
         */
        fun onResumeAll(seek: Boolean) {
            if (S_MAP.isNotEmpty()) {
                for ((key, value) in S_MAP.entries) {
                    value.onResume(key, seek)
                }
            }
        }

        fun clearAllVideo() {
            if (S_MAP.size > 0) {
                for ((key) in S_MAP.entries) {
                    releaseAllVideos(key)
                }
            }
            S_MAP.clear()
        }
        //重置视频播放器
        fun clearAllVideo(audioKey: String?) {
            if (S_MAP.size > 0) {
                for ((key) in S_MAP.entries) {
                    if (key != audioKey) releaseAllVideos(key)
                }
                S_MAP.filterKeys { it == audioKey }
            }
        }

        fun removeManager(key: String) {
            S_MAP.remove(key)
        }

        /**
         * 当前是否全屏状态
         *
         * @return 当前是否全屏状态， true代表是。
         */
        fun isFullState(activity: Activity?): Boolean {
            val vp =
                CommonUtil.scanForActivity(activity)
                    .findViewById<View>(Window.ID_ANDROID_CONTENT) as ViewGroup
            val full = vp.findViewById<View>(FULLSCREEN_ID)
            var gsyVideoPlayer: GSYVideoPlayer? = null
            if (full != null) {
                gsyVideoPlayer = full as GSYVideoPlayer
            }
            return gsyVideoPlayer != null
        }
    }


    /**
     * 暂停播放
     */
    private fun onPause(key: String) {
        if (getCustomManager(key).listener() != null) {
            getCustomManager(key).listener().onVideoPause()
        }
    }

    /**
     * 恢复播放
     */
    private fun onResume(key: String) {
        if (getCustomManager(key).listener() != null) {
            getCustomManager(key).listener().onVideoResume()
        }
    }


    /**
     * 恢复暂停状态
     *
     * @param seek 是否产生seek动作,直播设置为false
     */
    private fun onResume(key: String, seek: Boolean) {
        if (getCustomManager(key).listener() != null) {
            getCustomManager(key).listener().onVideoResume(seek)
        }
    }


    /**
     * 设置Ijkplayer 参数
     */
    private fun initVideoOption() {
        val list = ArrayList<VideoOptionModel>()
//        //开启硬解码
//        list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", 1))
//        //开启软解码
        list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "videotoolbox", 0))
        //过小会延迟
        list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "buffer_size", 3096))
        //无限读
        list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", 1))
        //分析码流时长
        list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "analyzemaxduration", 100))
        //  自动开始播放已准备好的
        list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", 0))
        //默认值48
        list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_CODEC, "skip_loop_filter", 48))
        //不设置会加长延迟
        list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "probesize", 10240))
        // 清空DNS,有时因为在APP里面要播放多种类型的视频(如:MP4,直播,直播平台保存的视频,和其它http视频), 有时会造成因为DNS的问题而报10000问题的
        list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_clear", 1))
        list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "flush_packets", 1))
        //最大缓存数
        list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", 0))
        //默认最小帧数2
        list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", 2))
        //丢帧,太卡可以尝试丢帧
        list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", 1))
        //关闭播放器缓冲，这个必须关闭，否则会出现播放一段时间后，一直卡主，控制台打印 FFP_MSG_BUFFERING_START
        list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", 0))
        setOptionModelList(list)
    }
}